/**
 * 
 */
package me.whily.nutzbook.module;

import java.util.Date;

import javax.servlet.http.HttpSession;

import me.whily.nutzbook.bean.User;
import me.whily.nutzbook.bean.UserProfile;
import me.whily.nutzbook.service.UserService;

import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Attr;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.filter.CheckSession;

/**
 * @author Administrator
 * @since 2015-07-27 11:40:18
 */
@Filters(@By(type=CheckSession.class, args={"me", "/"}))
@IocBean
@At("/user")
@Ok("json:{locked:'password|salt',ignoreNull:true}")
@Fail("http:500")
public class UserModule extends BaseModule {

	@Inject
	private UserService userService;
	
	@At("/")
    @Ok("jsp:jsp.user.list") // 真实路径是 /WEB-INF/jsp/user/list.jsp
    public void index() {
    }
	
	@At
    public Object query(@Param("name")String name, @Param("..")Pager pager) {
        Cnd cnd = Strings.isBlank(name)? null : Cnd.where("name", "like", "%"+name+"%");
        QueryResult qr = new QueryResult();
        qr.setList(dao.query(User.class, cnd, pager));
        pager.setRecordCount(dao.count(User.class, cnd));
        qr.setPager(pager);
        return qr; //默认分页是第1页,每页20条
    }
	 
	@At
	@Aop(TransAop.READ_COMMITTED)
    public Object delete(@Param("id")int id, @Attr("me")int me) {
        NutMap re = new NutMap();
		if (me == id) {
            return re.setv("ok", false).setv("msg", "不能删除当前用户!!");
        }
        dao.delete(User.class, id); // 再严谨一些的话,需要判断是否为>0
        dao.clear(UserProfile.class, Cnd.where("userId", "=", me));
        return re.setv("ok", true);
    }
	
	@At
    public Object update(@Param("..")User user) {
        NutMap re = new NutMap();
        String msg = checkUser(user, false);
        if (msg != null){
            return re.setv("ok", false).setv("msg", msg);
        }
        userService.updatePassword(user.getId(), user.getPassword());
        return re.setv("ok", true);
    }
	
	@At
	public Object add(@Param("..")User user) {
		NutMap re = new NutMap();
		String msg = checkUser(user, true);
		if (msg != null) {
			return re.setv("ok", false).setv("msg", msg);
		}
		user = userService.add(user.getName(), user.getPassword());
		return re.setv("ok", true).setv("data", user);
	}
	
	/**
	 * 新建或更新用户的校验方法
	 * @param user
	 * @param isCreate true：新建；false：更新
	 * @return
	 */
	private String checkUser(User user, boolean isCreate) {
		if (user == null)
			return "空对象";
		
		if (isCreate) {
			if (Strings.isBlank(user.getName()) || Strings.isBlank(user.getPassword()))
				return "用户名/密码不能为空";
		} else {
			if (Strings.isBlank(user.getPassword()))
				return "密码不能为空";
		}
		
		String passwd = user.getPassword().trim();
		if (6 > passwd.length() || passwd.length() > 12)
			return "密码长度必须在6到12位之间";
		
		if (isCreate) {
			if (dao.count(User.class, Cnd.where("name", "=", user.getName())) > 0)
				return "用户名已经存在";
		} else {
			if(user.getId() < 1)
				return "用户ID非法";
		}
		
		return null;
	}
	
	@At
	public int count() {
		return dao.count(User.class);
	}
	
	@Filters()
	@At
	public boolean login(HttpSession session, 
			@Param("username")String name,
			@Param("password")String password) {
		int userId = userService.fetch(name, password);
		if (userId > 0) {
			session.setAttribute("me", userId);
			return true;
		} else {
			return false;
		}
	}
	
	@At
	@Ok(">>:/")
	public void logout(HttpSession session) {
		session.invalidate();
	}
}
